package slh.favourite;

import slh.ConSql;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

@WebServlet("/favorite")
public class FavouriteSevlet extends HttpServlet {

    Connection conn = ConSql.getConnection();
    FavouriteService favoriteService=new FavouriteService(conn);

    public FavouriteSevlet() throws SQLException {
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        if ("check".equals(action)) {
            checkFavoriteStatus(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("userId") == null) {
            // 使用 JSON 格式返回错误信息
            out.print("{\"error\": \"请先登录\", \"redirect\": \"login.jsp\"}");
            return;
        }

        try {
            String userId = (String) session.getAttribute("userId");
            String action = request.getParameter("action");
            int contentId = Integer.parseInt(request.getParameter("contentId"));
            String contentType = request.getParameter("contentType");

            boolean success = false;
            if ("add".equals(action)) {
                success = favoriteService.addFavorite(userId, contentId, contentType);
            } else if ("remove".equals(action)) {
                success = favoriteService.removeFavorite(userId, contentId, contentType);
            }

            // 使用 print 而不是 write，避免额外的字符
            out.print("{\"success\": " + success + "}");

        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print("{\"error\": \"参数错误\"}");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            // 转义错误消息中的特殊字符
            String errorMsg = escapeJson(e.getMessage());
            out.print("{\"error\": \"服务器错误: " + errorMsg + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }

    private void checkFavoriteStatus(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        try {
            HttpSession session = request.getSession(false);
            String userId = session != null ? (String) session.getAttribute("userId") : null;

            if (userId == null) {
                out.print("{\"isFavorite\": false}");
                return;
            }

            int contentId = Integer.parseInt(request.getParameter("contentId"));
            String contentType = request.getParameter("contentType");

            boolean isFavorite = favoriteService.isFavorite(userId, contentId, contentType);
            out.print("{\"isFavorite\": " + isFavorite + "}");
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print("{\"error\": \"参数错误\"}");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            String errorMsg = escapeJson(e.getMessage());
            out.print("{\"error\": \"服务器错误: " + errorMsg + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }

    // 转义 JSON 中的特殊字符
    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}